package com.example.bookkeep.Bill;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.example.bookkeep.R;
import com.example.bookkeep.Utils.URLUtils;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddBillActivity extends AppCompatActivity {

    private RadioGroup rgType;
    private RadioButton rbExpense, rbIncome;
    private TextInputEditText etCategory, etPrice, etRemark;
    private EditText etAddTime;
    private MaterialButton btnSubmit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_bill);

        // 绑定控件
        rgType = findViewById(R.id.rgType);
        rbExpense = findViewById(R.id.rbExpense);
        rbIncome = findViewById(R.id.rbIncome);

        etCategory = findViewById(R.id.etCategory);
        etPrice = findViewById(R.id.etPrice);
        etRemark = findViewById(R.id.etRemark);
        etAddTime = findViewById(R.id.etAddTime);
        btnSubmit = findViewById(R.id.btnSubmit);

        // 默认创建时间设置为当天日期（yyyy-MM-dd）
        Calendar calendar = Calendar.getInstance();
        String defaultDate = String.format(Locale.getDefault(), "%04d-%02d-%02d",
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
        etAddTime.setText(defaultDate);

        // 点击日期输入框弹出日期选择器（只选日期，无时间）
        etAddTime.setOnClickListener(v -> showDatePickerDialog());

        // 提交按钮事件
        btnSubmit.setOnClickListener(v -> submitBill());
    }

    private void showDatePickerDialog() {
        Calendar calendar = Calendar.getInstance();

        DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                (DatePicker view, int year, int month, int dayOfMonth) -> {
                    String date = String.format(Locale.getDefault(), "%04d-%02d-%02d",
                            year, month + 1, dayOfMonth);
                    etAddTime.setText(date);
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );

        datePickerDialog.show();
    }

    private void submitBill() {
        // 获取账单类型，0 = 支出，1 = 收入
        int type = (rgType.getCheckedRadioButtonId() == R.id.rbExpense) ? 0 : 1;

        String category = etCategory.getText() != null ? etCategory.getText().toString().trim() : "";
        String priceStr = etPrice.getText() != null ? etPrice.getText().toString().trim() : "";
        String addTime = etAddTime.getText() != null ? etAddTime.getText().toString().trim() : "";
        String remark = etRemark.getText() != null ? etRemark.getText().toString().trim() : "";

        // 简单校验
        if (TextUtils.isEmpty(category)) {
            Toast.makeText(this, "请输入分类", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(priceStr)) {
            Toast.makeText(this, "请输入金额", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            Double.parseDouble(priceStr);
        } catch (NumberFormatException e) {
            Toast.makeText(this, "金额格式不正确", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(addTime)) {
            Toast.makeText(this, "请选择创建时间", Toast.LENGTH_SHORT).show();
            return;
        }

        // 构造提交的JSON数据，字段名要和后端对应
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("category", category);
        map.put("price", Double.parseDouble(priceStr));
        map.put("remark", remark);
        map.put("bookKeepDate", addTime);  // 只传日期，格式 yyyy-MM-dd

        String json = JSON.toJSONString(map);

        sendAddBillRequest(json);
    }

    private void sendAddBillRequest(String jsonBody) {
        OkHttpClient client = new OkHttpClient();

        SharedPreferences prefs = getSharedPreferences("auth", MODE_PRIVATE);
        String token = prefs.getString("token", "");

        RequestBody body = RequestBody.create(jsonBody, MediaType.parse("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url(URLUtils.BASE_URL + "/bookKeep")
                .addHeader("Authorization", "Bearer " + token)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() ->
                        Toast.makeText(AddBillActivity.this, "请求失败：" + e.getMessage(), Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();

                com.alibaba.fastjson.JSONObject res = com.alibaba.fastjson.JSONObject.parseObject(result);
                int code = res.getIntValue("code");
                String msg = res.getString("message");

                if (code == 1) {
                    runOnUiThread(() -> {
                        Toast.makeText(AddBillActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                        // 返回给调用页面，通知刷新
                        Intent intent = new Intent();
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    });
                } else {
                    runOnUiThread(() ->
                            Toast.makeText(AddBillActivity.this, "添加失败：" + (msg != null ? msg : "未知错误"), Toast.LENGTH_SHORT).show());
                }
            }
        });
    }
}
